/*
 * Created on Wed Jun 06 2018 by Ronnie Ren (zhaosong.ren) from Accenture
 *
 * Copyright (c) 2018 DingXing information & technology limited company.
 */

import { Injectable } from "@angular/core";
import { SqliteService } from "../../services/sqliteDB/sqlite.service";
import { CustomStorage } from "../transform/custom-storage";
import { StorageDto } from "../dto/storage.dto";
import { Observable } from "rxjs";


@Injectable()
export class StorageService {

  constructor(private sqliteService: SqliteService) {

  }


  fetchValueByKey(key: string): Observable<string> {
    let dto = new StorageDto();
    let sql = `select value from ${dto.table().tableName} where key = '${key}'`;
    return Observable.fromPromise(this.sqliteService.executeSqlWithResults<StorageDto>(sql, StorageDto))

      .map((values: Array<StorageDto>) => {
        if (values && values.length > 0 && values[0].value) {
          return values[0].value;
        }
        return null;
      });
  }


  update(storage: CustomStorage): Observable<boolean> {

    let dto = new StorageDto();
    dto.value = storage.value;
    dto.key = storage.key;
    return Observable.fromPromise(this.sqliteService.add(dto))
      .catch((err: object) => {
        return Observable.of({ code: -1 });
      })
      .flatMap((val) => {
        if (val && val["code"] === -1) {
          // exists
          let sql = `update ${dto.table().tableName} set value = ${dto.value} where key = '${dto.key}'`;
          return Observable.fromPromise(this.sqliteService.executeSql(sql)).map(() => true);
        }
        return Observable.of(true);
      });
  }





}
